package door.smartlift.top.config;

import door.smartlift.top.domain.SysUser;
import door.smartlift.top.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *
 * @author admin
 * @date 2017/12/25
 */

@Component
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;

    private static CredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher("md5");

    public MyShiroRealm() {

        super(credentialsMatcher);

    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token1= (UsernamePasswordToken) authenticationToken;

        String username = token1.getUsername();

        SysUser user=this.sysUserService.findUserByName(username);

        if (user==null){

            throw new UnknownAccountException("账号/密码错误");
        }

        if (user.getState().intValue()==0){

            throw new LockedAccountException("账号锁定");
        }

        String password=user.getPassword();

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                username,
                password ,
                ByteSource.Util.bytes(user.getSalt()),
                getName()
        );
        return authenticationInfo;
    }
}
